<template>
  <div class="page-container">
    <div class="page-header">
      <h1 class="page-title">数据源管理</h1>
      <p class="page-subtitle">管理和配置各种数据源连接</p>
    </div>

    <div class="action-bar">
      <div class="action-left">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索数据源名称"
          style="width: 300px"
          clearable
        >
        </el-input>
         <el-button type="primary" @click="fetchData">
          查询
        </el-button>
      </div>
      <div class="action-right">
        <el-button type="info" @click="handleRefreshAllStatus" :loading="refreshingStatus">
          🔄 刷新状态
        </el-button>
        <el-button type="primary" @click="handleCreate">
          ➕ 新增数据源
        </el-button>
      </div>
    </div>

    <div class="page-content">
      <el-table :data="filteredDataSources" v-loading="loading" style="width: 100%">
        <el-table-column prop="name" label="数据源名称" min-width="150" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">
              {{ getTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="host" label="主机地址" min-width="150" />
        <el-table-column prop="port" label="端口" width="80" />
        <el-table-column prop="database" label="数据库" min-width="120" />
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)" :loading="row.status === 'testing'">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="last_test_time" label="最后测试时间" width="180">
          <template #default="{ row }">
            {{ row.last_test_time || '未测试' }}
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleTest(row)">测试</el-button>
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getDatasourceList, 
  deleteDatasource, 
  testDatasourceById,
  refreshAllDatasourceStatus
} from '@/api/datasource'

const router = useRouter()
const loading = ref(false)
const refreshingStatus = ref(false)
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 数据源列表
const dataSources = ref([])

// 过滤后的数据源
const filteredDataSources = computed(() => {
  if (!searchKeyword.value) {
    return dataSources.value
  }
  return dataSources.value.filter(item => 
    item.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

// 获取类型标签类型
const getTypeTagType = (type) => {
  const typeMap = {
    'mysql': 'primary',
    'mongodb': 'success',
    'postgresql': 'warning',
    'oracle': 'info'
  }
  return typeMap[type] || 'info'
}

// 获取类型文本
const getTypeText = (type) => {
  const typeMap = {
    'mysql': 'MySQL',
    'mongodb': 'MongoDB',
    'postgresql': 'PostgreSQL',
    'oracle': 'Oracle'
  }
  return typeMap[type] || type.toUpperCase()
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const statusMap = {
    'connected': 'success',
    'disconnected': 'danger',
    'testing': 'warning',
    'unknown': 'info'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'connected': '已连接',
    'disconnected': '连接失败',
    'testing': '测试中...',
    'unknown': '未知'
  }
  return statusMap[status] || '未知'
}

// 处理新增
const handleCreate = () => {
  router.push('/datasource/create')
}

// 处理编辑
const handleEdit = (row) => {
  router.push(`/datasource/edit/${row.id}`)
}

// 处理测试连接
const handleTest = async (row) => {
  const originalStatus = row.status
  row.status = 'testing' // 临时状态
  
  try {
    const res = await testDatasourceById(row.id)
    // 更新行数据
    Object.assign(row, res.data)
    ElMessage.success('连接测试成功')
  } catch (error) {
    // 恢复原状态
    row.status = originalStatus
    if (error.response?.data?.message) {
      ElMessage.error(`连接测试失败: ${error.response.data.message}`)
      // 如果有返回的数据，更新状态
      if (error.response.data.data) {
        Object.assign(row, error.response.data.data)
      }
    } else {
      ElMessage.error('连接测试失败')
    }
  }
}

// 处理删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除数据源 "${row.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteDatasource(row.id)
    
    // 从列表中移除
    const index = dataSources.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      dataSources.value.splice(index, 1)
      total.value = Math.max(0, total.value - 1)
    }
    ElMessage.success('删除成功')
  } catch (error) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else if (error.message !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 处理刷新所有状态
const handleRefreshAllStatus = async () => {
  refreshingStatus.value = true
  try {
    await refreshAllDatasourceStatus()
    ElMessage.success('状态刷新成功')
    // 重新获取数据
    await fetchData()
  } catch (error) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('状态刷新失败')
    }
  } finally {
    refreshingStatus.value = false
  }
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchData()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const res = await getDatasourceList({
      page: currentPage.value,
      size: pageSize.value,
      keyword: searchKeyword.value
    })
    
    if (res.data) {
      dataSources.value = res.data
      total.value = res.total || res.data.length
    } else {
      dataSources.value = []
      total.value = 0
    }
  } catch (error) {
    ElMessage.error('获取数据失败')
    // 保留空数组，避免显示错误
    dataSources.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 监听搜索关键词变化
watch(searchKeyword, () => {
  currentPage.value = 1
  fetchData()
}, { debounce: 300 })

onMounted(() => {
  fetchData()
})
</script>

<style lang="scss" scoped>
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>